
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  utility;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import logger.PoolLogger;
import property.Order;
import database.RecordSearch;
import dbmanager.GetIdName;
import dbmanager.DBManager;
//import file.SearchRecord;

public class Rate_masterwithItemname 
{
	GetIdName gid;
	String FieldString="Field";
	String ConditionString="Condition";
	Vector<Object>FieldVector = new Vector<Object>();
	Vector<Object>ConditionVector = new Vector<Object>();
	String CONDITION="Condition";
	String spcharfield;
	String Condition;
	String CONDITIONFIELD="conditionfield";
	String CONDITIONOPERATOR="conditionoperator";
	String CONDITIONVALUE="conditionvalue";
	String LOGICALOPERATOR="logicaloperator";
	String QueryString ="";
	String TABLE_NAME="rate_master";
	final String ID="id";
	Vector<Object> IsFromMaster = new Vector<Object>(); 
	PoolLogger pl;
	
	public Rate_masterwithItemname() 
	{
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	public void setTableName(String TABLE_NAME)
	{
		this.TABLE_NAME = TABLE_NAME;
	}
	
	public void setData()
	{
		gid =new  GetIdName();
		
		CONDITION = gid.getId(CONDITION);
	}
	
	public void getData(String msg) 
	{
		try 
		{
			ResultSet rsfield= DBManager.getSelect("select spchar,beforeafter,fieldname,order1 from command where msgtype='Report'   and fieldname='Field' order by order1");
			ResultSet rs= DBManager.getSelect("select spchar,beforeafter,fieldname,order1 from command where msgtype='Report'   and fieldname='Type' order by order1");
			rs.next();
			rsfield.next();
			String spchar = rs.getString("spchar");
			spcharfield = rsfield.getString("spchar");
			int prevchar=0;
			while(prevchar!=-1)
			{
				String substring="";
				int currentchar = msg.indexOf(spchar, prevchar+1);
				if(currentchar==-1)
					substring = msg.substring(prevchar+1,msg.length());
				else
					substring = msg.substring(prevchar+1,currentchar);
				String split[] = substring.split(spcharfield);
				
				if(substring.contains(FieldString))
				{
					substring = substring.replace(split[0] ,"");
					String Split[]=substring.split(spcharfield);
					for(int i=0;i<Split.length;i++)
						FieldVector.add(Split[i].toLowerCase());
				}
				if(substring.contains(ConditionString))
				{
					substring = substring.replace(split[0] ,"");
					ConditionVector.add(substring);
				}	
				prevchar = currentchar;
			}
			
			if(FieldVector.size()==0) 
			{
				FieldVector.add(0, "*");
				FieldVector.add(1, "*");
			}	
			
			StringBuffer Result = new StringBuffer();
			QueryString = "Select ";
			for(int i=1;i<FieldVector.size();i++)
			{
				if(i>1)
					QueryString = QueryString +","+ FieldVector.get(i).toString();
				else
					QueryString = QueryString + FieldVector.get(i).toString();
				Result.append(FieldVector.get(i).toString().toLowerCase() + "\t");
			}	
			Result.append("\n");
			QueryString = QueryString + " From "+ TABLE_NAME ;
			ResultSet ResultIsFromMaster = DBManager.getSelect("select fieldname from command where msgtype='"+TABLE_NAME+"' and from_master='yes'");
			 
			while(ResultIsFromMaster.next())
			{
				IsFromMaster.add(ResultIsFromMaster.getString("fieldname").toLowerCase());
			}
			
			BuildCondition();
			System.out.println("The Query  is \n" +QueryString);
			ResultSet finalresultset = DBManager.getSelect(QueryString);
			 
			try 
			{
				if(FieldVector.contains("*"))
				{
					 finalresultset.next();
					 //ResultSet rsMetaData =  (ResultSet) finalresultset.getMetaData();
					 int tempcount=1;
					 while(tempcount!=finalresultset.getMetaData().getColumnCount()+1)
					 {
						 FieldVector.add(tempcount,finalresultset.getMetaData().getColumnName(tempcount++).toLowerCase());
					 }
					 FieldVector.remove(tempcount);
				}
				// replaces spcha for rate_master
				if(FieldVector.contains(ID))
					FieldVector.remove(ID);
				ResultSet rsrate_master = DBManager.getSelect("select fieldname,spchar from command where msgtype='"+TABLE_NAME+"' order by order1");
				Vector<Object> SpcharVector = new Vector<Object>();
				SpcharVector.addAll(FieldVector);
				while(rsrate_master.next())
				{
						String  fieldname = rsrate_master.getString("fieldname");
						if(FieldVector.contains(fieldname.toLowerCase()))
						{
							int index =FieldVector.indexOf(fieldname.toLowerCase(), 1);
							SpcharVector.remove(index);
							SpcharVector.add(index,rsrate_master.getString("spchar"));
						}
				}
				
				
				while(finalresultset.next())
				{
					for(int i=1;i<FieldVector.size();i++)
					{	
						String tempvalue=FieldVector.get(i).toString();
						String fieldvalue= finalresultset.getString(tempvalue);
						System.out.println(tempvalue);
						if(IsFromMaster.contains(tempvalue.toLowerCase()))
							fieldvalue = gid.getItem(fieldvalue);
						if(tempvalue.equals("item"))
						{
							//String path = Input.MASTERREPORTSPATH + gid.getId(fieldvalue) + "\\" +gid.getId(fieldvalue) +"_pv" + Input.FILRFORMAT;
							Hashtable<Object, Object>table = new Hashtable<Object, Object>();
							table.put("pid", gid.getId("itemcode"));
							table.put("pv", gid.getId(fieldvalue));
							/*SearchRecord sr = new SearchRecord(path);
							sr.fileOpen();
							String line[]=sr.getRecordSet(table);
							sr.fileClose();*/
							table.put("td","null");
							RecordSearch ps = new RecordSearch();
							ps.setConditionMap(table);
							String line[] = ps.getArrayFromResultSet();
							for(int l=0;l<line.length;l++)
							{
								String Split[]=line[l].split("\t");
								fieldvalue=gid.getItem(Split[0]);
							}
						}
						Result.append(SpcharVector.get(i) +"-" + fieldvalue+",");
					}
					Result.append("\n");
				}
			} 
			catch (Exception e) 
			{
			
				e.printStackTrace();
			}
			System.out.println("The Result of Query is \n"+Result);
			pl.info("The Result of Query is \n"+Result);
			pl.debug("The Result of Query is \n"+Result);
			pl.warn("The Result of Query is \n"+Result);
			pl.fatal("The Result of Query is \n"+Result);
			pl.error("The Result of Query is \n"+Result);
			pl.trace("The Result of Query is \n"+Result);
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
	}
	
	
	public void BuildCondition()
	{	
		property.Order order = new Order();
		Hashtable<Object, Object>table = new Hashtable<Object, Object>();
		table = order.getSequences(CONDITION);
		System.out.println(table);
		for(int k=0;k<ConditionVector.size();k++)
		{
			try 
			{
				if(k==0)
					QueryString =QueryString+ " where ";
				String tempCONDITIONFIELD="";
				String Split[]=ConditionVector.get(k).toString().split(spcharfield);
				String key = getKeyFromKey(table, CONDITIONFIELD);
				QueryString = QueryString + Split[Integer.parseInt(key)];
				tempCONDITIONFIELD = Split[Integer.parseInt(key)];
				key = getKeyFromKey(table, CONDITIONOPERATOR);
				QueryString = QueryString + Split[Integer.parseInt(key)];
				key = getKeyFromKey(table, CONDITIONVALUE);
				String tempvalue=Split[Integer.parseInt(key)];
				if(IsFromMaster.contains(tempCONDITIONFIELD.toLowerCase()))
						tempvalue = gid.getId(tempvalue);
				QueryString = QueryString + tempvalue;
				key = getKeyFromKey(table, LOGICALOPERATOR);
				if(!key.equals(""))
				QueryString = QueryString + " " + Split[Integer.parseInt(key)];
				QueryString = QueryString + " ";
			} 
			catch (Exception e) 
			{
				continue;
			}
		}
	}
	
	public String getKeyFromKey(Hashtable<Object, Object>hash,String value)
	{
	Enumeration hashen = hash.keys();
   	 while(hashen.hasMoreElements())
   	 { 
   		Object Key = hashen.nextElement();
   		if(hash.get(Key).toString().toLowerCase().equals(value.toLowerCase()))
   		{
   			return  Key.toString();	
   		}
   		
   	 }
   	 return " ";
   	 
	}
	
	public static void main(String[] args) 
	{	
		Rate_masterwithItemname rm =new  Rate_masterwithItemname();
		rm.setData();
		//rm.getData("|Field,Item,rate,unit,FD,TD|Condition,=,aab,item,and|Condition,>,2006-01-01,FD");
		//rm.getData("|Field,rate,item,buysell|condition,=,aab,item");
		rm.getData("|Field,rate,item");
	}
}
